package com.msb.mall.mallsearch.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.msb.common.dto.es.SkuESModel;
import com.msb.mall.mallsearch.MallSearchApplication;
import com.msb.mall.mallsearch.config.MallElasticSearchConfiguration;
import com.msb.mall.mallsearch.constant.ESConstant;
import com.msb.mall.mallsearch.service.ElasticSearchSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author zhangjiajun
 * @Email zhangjiajun@hydsoft.com
 * @Description
 * @Date 2025/7/24 11:13
 */
@Service
public class ElasticSearchSaveServiceImpl implements ElasticSearchSaveService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 实现上架数据存储到es的操作
     *
     * @param skuESModels
     * @return
     */
    @Override
    public Boolean productStatusUp(List<SkuESModel> skuESModels) throws IOException {
        //创建对应索引库   ==>  先创建product映射  --手动
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModels) {
            //绑定对应的索引库   product
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            //设置文档id
            indexRequest.id(skuESModel.getSkuId().toString());

            //设置文档
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(skuESModel);
            indexRequest.source(json, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        //执行批量请求   --批量保存数据到es中
        BulkResponse response = client.bulk(bulkRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
        //判断是否成功
        //获取批量操作是否有错误
        boolean saveStatus = !response.hasFailures();

        return saveStatus;
    }
}
